import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:HealthU/ViewModel/LoginViewModel.dart';
import 'package:shared_preferences/shared_preferences.dart';


Future<http.Response> sendRequest(String url, Map<String, String> headers, dynamic body, String method) async {
  print('URL: $url');
  print('Headers: $headers');
  print('Body: $body');

  http.Response response;

  if (method == 'GET') {
    response = await http.get(
      Uri.parse(url),
      headers: headers,
    );
  } else if (method == 'POST') {
    response = await http.post(
      Uri.parse(url),
      headers: headers,
      body: jsonEncode(body),
    );
  } else if (method == 'PUT') {
    response = await http.put(
      Uri.parse(url),
      headers: headers,
      body: jsonEncode(body),
    );
  } else {
    throw Exception('Unsupported HTTP method: $method');
  }
  print(method);
  print('Response: ${response.body}');

  return response;
}
class ApiService{

  static const String baseUrl = 'http://127.0.0.1:8000/api'; // 替换为你的实际接口地址

  final headers = {'Content-Type': 'application/json','accept': 'application/json'};

  // 读取数据
  Future<dynamic> loadData(String key) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();




    dynamic value = prefs.get(key);


    return value ?? '';
  }

  void showLog(Uri url,String body,Map<String,dynamic> headers){


  }

  Future<Map<String, dynamic>> login(String username, String password) async {

    var url = '$baseUrl/login'; // 替换为你的实际登录接口地址

    final body = {'username': username, 'password': password};

    final response = await sendRequest(url, headers, body, "POST");



    if (response.statusCode == 200) {
      final jsonData = jsonDecode(response.body);
      return jsonData;
    } else {
      throw Exception('登录请求失败');
    }

  }


  Future<Map<String, dynamic>> getUserInfo(int userId) async {


    final token = await loadData("_token");




    var url = '$baseUrl/user/$userId'; // 替换为你的实际登录接口地址

    final body = jsonEncode({});


    headers["Authorization"] = "Bearer " + token;


    final response = await sendRequest(url, headers, body, "GET");




    if (response.statusCode == 200) {
      final jsonData = jsonDecode(response.body);
      return jsonData;
    } else {
      throw Exception('用户信息请求失败');
    }

  }

}